(function($) {
  $.fn.china_city = function() {
    return this.each(function() {
      var selects = $(this).find('.city-select');
      var $province = $(this).find('.city-province')
      var $city = $(this).find('.city-city')

      return selects.change(function() {
        var $this, next_selects;
        $this = $(this);
        next_selects = selects.slice(selects.index(this) + 1);
        $("option:gt(0)", next_selects).remove();


        if (next_selects.first()[0] && $this.val() && !$this.val().match(/--.*--/)) {
          var path = "/china_city/";

          if ($this.is('.city-province')) {
            path = path + $province.val();
          } else if ($this.is('.city-city')) {
            path = path + $province.val() + '/' + $city.val();
          }

          $.get(path, function(data) {
            var i, len, option;
            if (data.data != null) {
              data = data.data;
            }
            for (i = 0, len = data.length; i < len; i++) {
              option = data[i];
              next_selects.first()[0].options.add(new Option(option, option));
            }
          });
        }
      });
    });
  };
  return $(document).on('ready page:load', function() {
    return $('.city-group').china_city();
  });
})(jQuery);
